package com.zhaoxi.project.crm.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson2.JSONObject;
import com.zhaoxi.common.utils.DateUtils;
import com.zhaoxi.common.utils.StringUtils;
import com.zhaoxi.common.utils.file.FileUploadUtils;
import com.zhaoxi.framework.config.ZhaoXiConfig;
import com.zhaoxi.project.crm.utils.ResumeUtil;
import com.zhaoxi.project.md.domain.MdPartner;
import com.zhaoxi.project.md.service.impl.MdPartnerServiceImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zhaoxi.framework.aspectj.lang.annotation.Log;
import com.zhaoxi.framework.aspectj.lang.enums.BusinessType;
import com.zhaoxi.framework.web.controller.BaseController;
import com.zhaoxi.framework.web.domain.AjaxResult;
import com.zhaoxi.common.utils.poi.ExcelUtil;
import com.zhaoxi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 客户跟踪Controller
 *
 * @author zhaoxi
 * @date 2023-07-07
 */
@RestController
@RequestMapping("/crm/lead")
public class CrmLeadController extends BaseController {
    /**
     * crm_lead 和mdPartner都是一个类，主键相同。都是基于partner
     */
    @Autowired
    private MdPartnerServiceImpl mdPartnerService;

    /**
     * 查询客户跟踪列表
     */
    @PreAuthorize("@ss.hasPermi('md:partner:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdPartner mdPartner) {
        startPage();
        List<MdPartner> list = mdPartnerService.selectCrmLeadList(mdPartner);
        return getDataTable(list);
    }

    /**
     * 导出客户跟踪列表
     */
    @PreAuthorize("@ss.hasPermi('md:partner:export')")
    @Log(title = "客户跟踪", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdPartner mdPartner) {
        List<MdPartner> list = mdPartnerService.selectCrmLeadList(mdPartner);
        ExcelUtil<MdPartner> util = new ExcelUtil<MdPartner>(MdPartner.class);
        util.exportExcel(response, list, "客户跟踪数据");
    }

    /**
     * 获取客户跟踪详细信息
     */
    @PreAuthorize("@ss.hasPermi('md:partner:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(mdPartnerService.selectCrmLeadById(id));
    }

    /**
     * 新增客户跟踪
     */
    @PreAuthorize("@ss.hasPermi('md:partner:add')")
    @Log(title = "客户跟踪", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdPartner mdPartner) {
        return toAjax(mdPartnerService.insertCrmLead(mdPartner));
    }

    /**
     * 修改客户跟踪
     */
    @PreAuthorize("@ss.hasPermi('md:partner:edit')")
    @Log(title = "客户跟踪", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdPartner mdPartner) {
        if (mdPartner.getId() == null){
            return error("id不能为空");
        }
        return toAjax(mdPartnerService.updateCrmLead(mdPartner));
    }

    /**
     * 删除客户跟踪
     */
    @PreAuthorize("@ss.hasPermi('md:partner:remove')")
    @Log(title = "客户跟踪", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(mdPartnerService.deleteCrmLeadByIds(ids));
    }


    /**
     * 删除客户跟踪
     */
    @PreAuthorize("@ss.hasPermi('md:partner:add')")
    @Log(title = "客户跟踪", businessType = BusinessType.DELETE)
    @PostMapping("/uploadResume")
    public AjaxResult uploadResume(MultipartFile file,boolean updateSupport) throws Exception {
        MdPartner partner = null;
        if (file.isEmpty()) {
            logger.warn("文件不能为空");
            return AjaxResult.error("文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        logger.info("originalFilename:" + originalFilename);
        if (StringUtils.isEmpty(originalFilename)) {
            logger.warn("文件名称不能为空");
            return AjaxResult.error("文件名称不能为空");
        }
        byte[] buffer;
        buffer = ResumeUtil.getInputStream(file);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
        InputStream inputStream = file.getInputStream();
        String jsonStr = null;
        if (originalFilename.contains("51job")) {
            jsonStr = ResumeUtil.get51(inputStream);
        } else if (originalFilename.contains("新安人才网")) {
            jsonStr = ResumeUtil.getXinAnRenCai(byteArrayInputStream);
        } else if (originalFilename.contains("58简历")) {
            jsonStr = ResumeUtil.get58(byteArrayInputStream);
        } else if (originalFilename.contains("智联")) {
            jsonStr = ResumeUtil.getZhiLian(byteArrayInputStream);
        } else if (originalFilename.contains("Boss直聘")) {
            jsonStr = ResumeUtil.getBossZhiPin(byteArrayInputStream);
        } else {
            jsonStr = ResumeUtil.getBossZhiPin(byteArrayInputStream);
        }
        partner = JSONObject.parseObject(jsonStr, MdPartner.class);

        synchronized (CrmLeadController.class) {
            // resume.setFile(buffer);
            String filePath = ZhaoXiConfig.getUploadPath();
            logger.info("路径" + filePath);
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
//            partner.setFileName(fileName);
            // String url = serverConfig.getUrl() + fileName;
            partner.setUpdateBy(this.getUsername());
//            MdPartnerService.insertMdPartner(resume);
            AjaxResult ajax = AjaxResult.success();
            // ajax.put("url", url);
            // resume.setFile(null);
            ajax.put("partner", JSONObject.parse(JSONObject.toJSONString(partner)));

            //手机号如果是空的，直接存数据库里，并且返回了。等人事手动识别 2023年5月26日, PM 10:10:03
            if (partner.getMobile() == null) {
                mdPartnerService.insertMdPartner(partner);
                return AjaxResult.error("文件未自动识别到手机号：" + originalFilename);
            }
            //检查手机号是否存在过数据，插入或者更新 2023年5月26日, PM 10:10:07
            MdPartner exiteMdPartner = mdPartnerService.selectMdPartnerByMobile(partner);
            if (exiteMdPartner == null) {
                partner.setUserId(this.getUserId());
                partner.setEnableFlag("0");
                partner.setIsCustomer("0");
                partner.setCreateBy(this.getUsername());
                partner.setUpdateBy(this.getUsername());
                partner.setCreateTime(DateUtils.getNowDate());
                partner.setUpdateTime(DateUtils.getNowDate());
                mdPartnerService.insertMdPartner(partner);
            }
            if (exiteMdPartner != null & updateSupport) {
                partner.setRemark(DateUtils.getDate() + ",再次投递");
                partner.setId(exiteMdPartner.getId());
                if (exiteMdPartner.getUserId() == null){
                    exiteMdPartner.setUserId(this.getUserId());
                }
                partner.setUserId(exiteMdPartner.getUserId());
                partner.setUpdateBy(this.getUsername());
                partner.setUpdateTime(DateUtils.getNowDate());
                mdPartnerService.updateMdPartner(partner);
            }
            MdPartner exiteCrmLead = mdPartnerService.selectCrmLeadById(partner.getId());
            if (exiteCrmLead == null){
                partner.setSalesStage("1");
                partner.setRemark(DateUtils.getDate() + ",初次导入");
                partner.setCreateBy(this.getUsername());
                partner.setUpdateBy(this.getUsername());
                partner.setCreateTime(DateUtils.getNowDate());
                partner.setUpdateTime(DateUtils.getNowDate());
                mdPartnerService.insertCrmLead(partner);
            }else{
                exiteCrmLead.setRemark(DateUtils.getDate() + ",再次投递");
                if (exiteCrmLead.getUserId() == null){
                    exiteCrmLead.setUserId(this.getUserId());
                }
                exiteCrmLead.setUpdateBy(this.getUsername());
                exiteCrmLead.setUpdateTime(DateUtils.getNowDate());
                mdPartnerService.updateCrmLead(exiteCrmLead);
            }
            return ajax;
        }
    }

    @PreAuthorize("@ss.hasPermi('md:partner:query')")
    @GetMapping("/commentList/{id}")
    public AjaxResult commentList(@PathVariable("id") Long id) {
        MdPartner mdPartner = new MdPartner();
        mdPartner.setId(id);
        List<MdPartner> list = mdPartnerService.selectCrmLeadCommentList(mdPartner);
        return AjaxResult.success("list", list);
    }

    @PreAuthorize("@ss.hasPermi('md:partner:query')")
    @GetMapping("/resumeInfo/{id}")
    public AjaxResult resumeInfo(@PathVariable("id") Long id) {
        MdPartner mdPartner = mdPartnerService.selectCrmLeadResumeInfo(id);
        return AjaxResult.success(mdPartner);
    }
}
